<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>病历管理</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script src="/js/jquery.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <style>
        body { margin: 0; padding: 0; background: #f5f6fa; display: flex; min-height: 100vh; }
        .main-wrapper {
            display: flex;
            width: 100%;
        }
        .sidebar {
            width: 240px;
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            padding: 0;
            box-shadow: 2px 0 8px rgba(0,0,0,0.07);
            min-height: 100vh;
            color: #fff;
            display: flex;
            flex-direction: column;
            align-items: stretch;
        }
        .sidebar h3 {
            color: #fff;
            font-weight: bold;
            text-align: center;
            padding: 32px 0 16px 0;
            letter-spacing: 2px;
            font-size: 1.3rem;
            margin-bottom: 0;
        }
        .sidebar ul {
            list-style: none;
            padding: 0 0 32px 0;
            margin: 0;
            flex: 1;
        }
        .sidebar ul li {
            margin: 0;
        }
        .sidebar ul li a {
            display: flex;
            align-items: center;
            padding: 14px 32px;
            color: #e3e6f0;
            text-decoration: none;
            font-size: 1.08rem;
            border-left: 4px solid transparent;
            transition: background 0.2s, color 0.2s, border-color 0.2s;
            border-radius: 0 24px 24px 0;
            margin-bottom: 2px;
        }
        .sidebar ul li a:hover,
        .sidebar ul li a.active {
            background: rgba(255,255,255,0.12);
            color: #fff;
            border-left: 4px solid #f6c23e;
            font-weight: bold;
        }
        .sidebar ul li a .icon {
            margin-right: 10px;
            font-size: 1.2em;
        }
        .main-content {
            flex-grow: 1;
            padding: 20px;
            background-color: #f5f6fa;
        }
        .info-card {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .form-group label { font-weight: bold; }
    </style>
</head>
<body>

<div class="main-wrapper">
    <div class="sidebar">
        <h3>医院病例管理系统</h3>
        <ul>
<%--            <li><a href="/adminStatistics">统计分析</a></li>--%>
            <li><a href="/adminUserList">用户管理</a></li>
            <li><a href="/adminMedicalRecordList" class="active">病历管理</a></li>
            <li><a href="/adminPersonalCenter">个人信息管理</a></li>
            <li><a href="/adminMedicalTemplate">病历模板管理</a></li>
            <li><a href="/adminUpdateRequest">信息修改申请</a></li>
        </ul>
    </div>
    
    <div class="main-content">
        <div class="info-card">
            <h2>病历列表</h2>
            
            <!-- 搜索和筛选 -->
            <div class="mb-3">
                <input type="text" id="medicalRecordSearchInput" class="form-control" placeholder="输入诊断结果搜索">
            </div>
            
            <!-- 添加病历按钮 -->
            <div class="mb-3 text-right">
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addMedicalRecordModal">新增病历</button>
            </div>
            
            <!-- 病历列表表格 -->
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>病历ID</th>
                        <th>挂号ID</th>
                        <th>患者姓名</th> <%-- TODO: 需要后端关联 register 和 user 表 --%>
                        <th>医生姓名</th> <%-- TODO: 需要后端关联 register 和 user 表 --%>
                        <th>挂号时间</th>
                        <th>主诉</th>
                        <th>诊断结果</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="medicalRecordTableBody">
                    <%-- 病历数据将在这里加载 --%>
                </tbody>
            </table>
            
            <!-- 分页控件 -->
            <nav>
                <ul class="pagination justify-content-center" id="pagination">
                    <%-- 分页按钮将在这里加载 --%>
                </ul>
            </nav>
            
            <div id="loading" class="text-center" style="display: none;">加载中...</div>
            <div id="error" class="alert alert-danger" style="display: none;">加载失败</div>
        </div>
    </div>
</div>

<script>
$(function(){
    let currentPage = 1;
    const pageSize = 10; // 与后端 pageSize 默认值一致

    // 获取病历列表数据
    function loadMedicalRecords() {
        $('#loading').show();
        $('#error').hide();
        const keyword = $('#medicalRecordSearchInput').val();

        $.ajax({
            url: '/medical/admin/list',
            type: 'GET',
            data: {
                pageNum: currentPage,
                pageSize: pageSize,
                keyword: keyword
            },
            success: function(res){
                $('#loading').hide();
                if(res.code === 0 && res.data){
                    const pageData = res.data; // 后端返回的是 Page 对象
                    const medicalRecords = pageData.records; // 实际的病历列表
                    const total = pageData.total;

                    const $tbody = $('#medicalRecordTableBody');
                    $tbody.empty(); // 清空现有数据

                    if (medicalRecords.length === 0) {
                        $tbody.append('<tr><td colspan="7" class="text-center">无病历数据</td></tr>');
                        $('#pagination').empty();
                        return;
                    }

                    medicalRecords.forEach(record => {
                        const $row = $('<tr>');
                        $row.append($('<td>').text(record.id));
                        $row.append($('<td>').text(record.registerId));
                        $row.append($('<td>').text(record.patientUsername || '-'));
                        $row.append($('<td>').text(record.doctorUsername || '-'));
                        $row.append($('<td>').text(record.registerTime ? new Date(record.registerTime).toLocaleString() : '-'));
                        $row.append($('<td>').text(record.readme || '-'));
                        $row.append($('<td>').text(record.diagnosis || '-'));

                        const $deleteButton = $('<button>').addClass('btn btn-sm btn-danger delete-btn me-2').text('删除').attr('data-id', record.id); // 添加 me-2 类
                        const $editButton = $('<button>').addClass('btn btn-sm btn-primary edit-btn').text('编辑').attr('data-id', record.id).attr('data-bs-toggle', 'modal').attr('data-bs-target', '#editMedicalRecordModal'); // 添加编辑按钮

                        const $actionsCell = $('<td>').append($editButton).append($deleteButton); // 将编辑按钮添加到操作列
                        $row.append($actionsCell);

                        $tbody.append($row);

                         // TODO: 如果后端不关联查询，这里可能需要额外调用接口获取患者和医生姓名
                    });

                    // 更新分页控件
                    updatePagination(total);

                } else {
                    $('#error').text(res.message || '获取病历列表失败').show();
                    $('#pagination').empty();
                }
            },
            error: function(){
                $('#loading').hide();
                $('#error').text('请求失败，请稍后重试').show();
                $('#pagination').empty();
            }
        });
    }

    // 更新分页控件
    function updatePagination(total) {
        const $pagination = $('#pagination');
        $pagination.empty();
        const totalPages = Math.ceil(total / pageSize);

        if (totalPages <= 1) {
            return; // 少于等于1页不显示分页
        }

        // 添加首页和上一页按钮
        $pagination.append(createPaginationItem(1, '首页', currentPage === 1));
        $pagination.append(createPaginationItem(currentPage - 1, '上一页', currentPage === 1));

        // 添加页码
        // 这里只显示当前页附近的一些页码，避免页码过多
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);

        if (startPage > 1) {
            $pagination.append(createPaginationItem(1, 1));
            if (startPage > 2) {
                $pagination.append($('<li>').addClass('page-item disabled').append($('<span>').addClass('page-link').text('...')));
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            $pagination.append(createPaginationItem(i, i, i === currentPage));
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                $pagination.append($('<li>').addClass('page-item disabled').append($('<span>').addClass('page-link').text('...')));
            }
            $pagination.append(createPaginationItem(totalPages, totalPages));
        }

        // 添加下一页和尾页按钮
        $pagination.append(createPaginationItem(currentPage + 1, '下一页', currentPage === totalPages));
        $pagination.append(createPaginationItem(totalPages, '尾页', currentPage === totalPages));
    }

    // 辅助函数：创建分页链接项
    function createPaginationItem(page, text, isDisabled = false) {
            const $li = $('<li>').addClass('page-item');
        if (isDisabled) {
            $li.addClass('disabled');
        }
        if (page === currentPage && !isDisabled) {
                $li.addClass('active');
            }
        const $link = $('<a>').addClass('page-link').attr('href', '#').text(text).attr('data-page', page);
            $li.append($link);
        return $li;
    }

    // 删除病历
    function deleteMedicalRecord(recordId) {
        $.ajax({
            url: '/medical/admin/' + recordId,
            type: 'DELETE',
            success: function(res){
                if(res.code === 0){
                    alert('病历删除成功');
                    loadMedicalRecords(); // 刷新列表
                } else {
                    alert(res.message || '删除失败');
                }
            },
            error: function(){
                alert('删除失败，请稍后重试');
            }
        });
    }

    // 使用事件委托为动态添加的删除按钮绑定点击事件
    $('#medicalRecordTableBody').on('click', '.delete-btn', function(){
        const recordId = $(this).data('id');
        if (confirm('确定要删除此病历吗？')) {
            deleteMedicalRecord(recordId);
        }
    });

    // 搜索框输入事件
    $('#medicalRecordSearchInput').on('input', function(){
        currentPage = 1; // 搜索时重置到第一页
        loadMedicalRecords();
    });

    // 分页点击事件 (事件委托)
    $('#pagination').on('click', '.page-link', function(e){
        e.preventDefault(); // 阻止默认跳转
        const page = $(this).data('page'); // 获取页码
        const $parentLi = $(this).parent('li');

        if ($parentLi.hasClass('disabled') || $parentLi.hasClass('active')) {
            return; // 如果是禁用或当前页，不执行操作
        }

        if (page >= 1 && page <= Math.ceil(total / pageSize)) { // 确保页码有效
             currentPage = parseInt(page);
             loadMedicalRecords();
        }
    });

    // 保存新增病历按钮点击事件
    $('#saveMedicalRecordBtn').click(function(){
        const medicalRecordData = {
            registerId: $('#addRegisterId').val(),
            readme: $('#addReadme').val(),
            present: $('#addPresent').val(),
            presentTreat: $('#addPresentTreat').val(),
            history: $('#addHistory').val(),
            allergy: $('#addAllergy').val(),
            physique: $('#addPhysique').val(),
            proposal: $('#addProposal').val(),
            careful: $('#addCareful').val(),
            diagnosis: $('#addDiagnosis').val(),
            cure: $('#addCure').val()
        };
        

        $.ajax({
            url: '/medical/admin/add',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(medicalRecordData),
            success: function(res){
                if(res.code === 0){
                    alert('病历添加成功');
                    const addMedicalRecordModal = bootstrap.Modal.getInstance(document.getElementById('addMedicalRecordModal'));
                    addMedicalRecordModal.hide(); // 关闭模态框
                    loadMedicalRecords(); // 刷新列表
                } else {
                    alert(res.message || '病历添加失败');
                }
            },
            error: function(){
                alert('病历添加失败，请稍后重试');
            }
        });
    });

    // 页面加载时获取病历列表
    loadMedicalRecords();

    // 加载挂号记录并填充下拉框
    function loadRegistersForSelect() {
        $.ajax({
            url: '/admin/register/listForMedicalRecord',
            type: 'GET',
            success: function(res) {
                if (res.code === 0 && res.data) {
                    const $select = $('#addRegisterId');
                    $select.empty();
                    $select.append($('<option>').val('').text('请选择挂号记录'));
                    res.data.forEach(register => {
                        // 在这里检查 register 对象和 optionText 变量的值
                        console.log("当前挂号记录对象:", register); // 新增：打印原始对象
                        const optionText = '挂号ID: ' + register.id + ' - 患者: ' + register.patientUsername + ' - 医生: ' + register.doctorUsername;
                        console.log("生成的选项文本:", optionText); // 新增：打印生成的文本
                        $select.append($('<option>').val(register.id).text(optionText));
                    });
                } else {
                    console.error('获取挂号记录失败:', res.message);
                }
            },
            error: function() {
                console.error('获取挂号记录失败');
            }
        });
    }

    // 加载病历模板并填充下拉框
    function loadMedicalTemplatesForSelect() {
        $.ajax({
            url: '/admin/medical/templates/list',
            type: 'GET',
            success: function(res) {
                if (res.code === 0 && res.data) {
                    const $select = $('#templateSelect');
                    $select.empty();
                    $select.append($('<option>').val('').text('请选择病历模板 (可选)'));
                    res.data.forEach(template => {
                        $select.append($('<option>').val(template.id).text(template.name));
                    });
                } else {
                    console.error('获取病历模板失败:', res.message);
                }
            },
            error: function() {
                console.error('获取病历模板失败');
            }
        });
    }

    // 根据模板ID获取模板内容并填充表单
    function fillFormWithTemplate(templateId) {
        if (!templateId) {
            // 如果选择了"请选择模板"，则清空表单内容（挂号记录除外）
            $('#addReadme').val('');
            $('#addPresent').val('');
            $('#addPresentTreat').val('');
            $('#addHistory').val('');
            $('#addAllergy').val('');
            $('#addPhysique').val('');
            $('#addProposal').val('');
            $('#addCareful').val('');
            $('#addDiagnosis').val('');
            $('#addCure').val('');
            return;
        }
        $.ajax({
            url: '/admin/medical/templates/' + templateId, // 假设后端根据ID获取病历模板详情的接口
            type: 'GET',
            success: function(res) {
                if (res.code === 0 && res.data) {
                    try {
                        const templateContent = JSON.parse(res.data.content);
                        $('#addReadme').val(templateContent.readme || '');
                        $('#addPresent').val(templateContent.present || '');
                        $('#addPresentTreat').val(templateContent.present_treat || '');
                        $('#addHistory').val(templateContent.history || '');
                        $('#addAllergy').val(templateContent.allergy || '');
                        $('#addPhysique').val(templateContent.physique || '');
                        $('#addProposal').val(templateContent.proposal || '');
                        $('#addCareful').val(templateContent.careful || '');
                        $('#addDiagnosis').val(templateContent.diagnosis || '');
                        $('#addCure').val(templateContent.cure || '');
                    } catch (e) {
                        console.error('解析模板内容失败:', e);
                        alert('加载模板内容失败，模板内容格式不正确。');
                    }
                } else {
                    console.error('获取模板详情失败:', res.message);
                    alert('获取模板详情失败。');
                }
            },
            error: function() {
                console.error('获取模板详情失败');
                alert('获取模板详情失败，请稍后重试。');
            }
        });
    }

    // 在模态框显示前加载挂号记录和病历模板
    $('#addMedicalRecordModal').on('show.bs.modal', function (event) {
        loadRegistersForSelect();
        loadMedicalTemplatesForSelect();
        $('#addMedicalRecordForm')[0].reset(); // 重置表单，包括模板选择框
    });

    // 监听病历模板选择框的变化
    $('#templateSelect').on('change', function(){
        const selectedTemplateId = $(this).val();
        fillFormWithTemplate(selectedTemplateId);
    });

    // 加载病历详情并填充编辑模态框
    function loadMedicalRecordForEdit(recordId) {
        $.ajax({
            url: '/medical/admin/' + recordId, // 调用后端获取病历详情的接口
            type: 'GET',
            success: function(res) {
                if (res.code === 0 && res.data) {
                    const record = res.data;
                    $('#editMedicalRecordId').val(record.id);
                    // 编辑时挂号记录不可修改，只显示
                    $('#editRegisterIdDisplay').text('挂号ID: ' + record.registerId);
                    $('#editReadme').val(record.readme || '');
                    $('#editPresent').val(record.present || '');
                    $('#editPresentTreat').val(record.presentTreat || '');
                    $('#editHistory').val(record.history || '');
                    $('#editAllergy').val(record.allergy || '');
                    $('#editPhysique').val(record.physique || '');
                    $('#editProposal').val(record.proposal || '');
                    $('#editCareful').val(record.careful || '');
                    $('#editDiagnosis').val(record.diagnosis || '');
                    $('#editCure').val(record.cure || '');
                } else {
                    alert('获取病历详情失败: ' + (res.message || ''));
                }
            },
            error: function() {
                alert('获取病历详情失败，请稍后重试。');
            }
        });
    }

    // 监听编辑按钮点击事件 (事件委托)
    $('#medicalRecordTableBody').on('click', '.edit-btn', function(){
        const recordId = $(this).data('id');
        if (recordId) {
            loadMedicalRecordForEdit(recordId);
        }
    });

    // 保存编辑后的病历
    $('#saveEditMedicalRecordBtn').click(function(){
        const medicalRecordData = {
            id: $('#editMedicalRecordId').val(),
            // 挂号ID在编辑时不可修改
            // registerId: $('#editRegisterId').val(), // 假设有一个隐藏字段存放挂号ID
            readme: $('#editReadme').val(),
            present: $('#editPresent').val(),
            presentTreat: $('#editPresentTreat').val(),
            history: $('#editHistory').val(),
            allergy: $('#editAllergy').val(),
            physique: $('#editPhysique').val(),
            proposal: $('#editProposal').val(),
            careful: $('#editCareful').val(),
            diagnosis: $('#editDiagnosis').val(),
            cure: $('#editCure').val()
        };

        $.ajax({
            url: '/medical/admin/update', // 调用后端更新病历的接口
            type: 'POST', // 或者 PUT
            contentType: 'application/json',
            data: JSON.stringify(medicalRecordData),
            success: function(res){
                if(res.code === 0){
                    alert('病历修改成功');
                    const editMedicalRecordModal = bootstrap.Modal.getInstance(document.getElementById('editMedicalRecordModal'));
                    editMedicalRecordModal.hide(); // 关闭模态框
                    loadMedicalRecords(); // 刷新列表
                } else {
                    alert(res.message || '病历修改失败');
                }
            },
            error: function(){
                alert('病历修改失败，请稍后重试');
            }
        });
    });
});
</script>

<!-- 新增病历模态框 -->
<div class="modal fade" id="addMedicalRecordModal" tabindex="-1" aria-labelledby="addMedicalRecordModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addMedicalRecordModalLabel">新增病历</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addMedicalRecordForm">
                    <div class="mb-3">
                        <label for="addRegisterId" class="form-label">挂号记录</label>
                        <select class="form-control" id="addRegisterId" required>
                            <option value="">请选择挂号记录</option>
                            <%-- 挂号记录选项将在这里加载 --%>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="templateSelect" class="form-label">选择病历模板</label>
                        <select class="form-control" id="templateSelect">
                            <option value="">请选择病历模板 (可选)</option>
                            <%-- 病历模板选项将在这里加载 --%>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="readme" class="form-label">主诉</label>
                        <textarea class="form-control" id="addReadme" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="present" class="form-label">现病史</label>
                        <textarea class="form-control" id="addPresent" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="present_treat" class="form-label">现病治疗情况</label>
                        <textarea class="form-control" id="addPresentTreat" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="history" class="form-label">既往史</label>
                        <textarea class="form-control" id="addHistory" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="allergy" class="form-label">过敏史</label>
                        <textarea class="form-control" id="addAllergy" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="physique" class="form-label">体格检查</label>
                        <textarea class="form-control" id="addPhysique" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="proposal" class="form-label">检查/检验建议</label>
                        <textarea class="form-control" id="addProposal" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="careful" class="form-label">注意事项</label>
                        <textarea class="form-control" id="addCareful" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="diagnosis" class="form-label">诊断结果</label>
                        <textarea class="form-control" id="addDiagnosis" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="cure" class="form-label">处理意见</label>
                        <textarea class="form-control" id="addCure" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="saveMedicalRecordBtn">保存病历</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑病历模态框 -->
<div class="modal fade" id="editMedicalRecordModal" tabindex="-1" aria-labelledby="editMedicalRecordModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editMedicalRecordModalLabel">编辑病历</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editMedicalRecordForm">
                    <input type="hidden" id="editMedicalRecordId"> <!-- 隐藏字段存放病历ID -->
                    <div class="mb-3">
                        <label for="editRegisterIdDisplay" class="form-label">挂号记录</label>
                        <span id="editRegisterIdDisplay" class="form-control-plaintext"></span> <!-- 显示挂号记录信息，不可编辑 -->
                    </div>
                    <!-- 以下字段与新增病历模态框中的字段类似，用于编辑 -->
                    <div class="mb-3">
                        <label for="editReadme" class="form-label">主诉</label>
                        <textarea class="form-control" id="editReadme" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editPresent" class="form-label">现病史</label>
                        <textarea class="form-control" id="editPresent" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editPresentTreat" class="form-label">现病治疗情况</label>
                        <textarea class="form-control" id="editPresentTreat" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editHistory" class="form-label">既往史</label>
                        <textarea class="form-control" id="editHistory" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editAllergy" class="form-label">过敏史</label>
                        <textarea class="form-control" id="editAllergy" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editPhysique" class="form-label">体格检查</label>
                        <textarea class="form-control" id="editPhysique" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editProposal" class="form-label">检查/检验建议</label>
                        <textarea class="form-control" id="editProposal" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editCareful" class="form-label">注意事项</label>
                        <textarea class="form-control" id="editCareful" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editDiagnosis" class="form-label">诊断结果</label>
                        <textarea class="form-control" id="editDiagnosis" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editCure" class="form-label">处理意见</label>
                        <textarea class="form-control" id="editCure" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEditMedicalRecordBtn">保存修改</button>
            </div>
        </div>
    </div>
</div>

</body>
</html> 